﻿@using Page = viBook.Models.Page
@model Page
<script id="ChapterTemplate" type="text/html">
	<img class="cropable" data-bind="attr: {src: src}"></img>
</script>
<!-- This is the NORMAL template -->
<script id="TagTemplate" type="text/html">
	<div class="tag_label tag_label tag_label_inactive" data-bind="style:{marginTop: y,marginLeft:x,width:w,height:h}">
		<a href="#" data-bind="click: removeTag">Delete</a>|
		<a href="#" data-bind="click: editTag">Edit tag</a>|
		<a href="#" data-bind="click: editText">Edit text</a>
		<br/>
		<span class="translatedText">${convertedText}</span>
	</div>
</script>
<script type="text/javascript">
	  function ParseRect(positionStr) {
		var positionArray = positionStr.split("_");
		return {
			x: parseInt(positionArray[0]),
			y: parseInt(positionArray[1]),
			w: parseInt(positionArray[2]),
			h: parseInt(positionArray[3])
		};
	}
	  
	function Picture(id, src) {
		return {
			id: id,
			src: ko.observable(src)
		};
	}

	function Tag(id, positionStr, convertedText, translatedText) {
		var rec = ParseRect(positionStr);
		return {
			id: id,
			positionStr:positionStr,
			y: ko.observable(rec.y + 'px'),
			x: ko.observable(rec.x + 'px'),
			x2: ko.observable((rec.x + rec.w) + 'px'),
			w: ko.observable(rec.w + 'px'),
			h: ko.observable(rec.h + 'px'),
			convertedText: ko.observable(convertedText),
			translatedText: ko.observable(translatedText),
			removeTag: function() {
				viewmodel.tagCollection.remove(this);
				if (this.id > 0) {
					deletedTags[deletedTags.length] = this.id;
				} else {
					for (var i = 0, length = addedTags.length; i < length; i++) {
						if (addedTags[i].id === this.id) {
							$(addedTags).remove(this);
							break;
						}
					}
				}
			},
			editTag: function() {
				var rectArray = [rec.x, rec.y, rec.w, rec.h];
				jcropApi = $.Jcrop('.cropable');
				jcropApi.setSelect(rectArray);
			},
			editText: function() {
				$('#converted-text').val(this.convertedText());
				$('#translated-text').val(this.translatedText());
				$('#add-tag-modal').toggle();
			}
		};
	}
	var newlyCreatedTagId = -1,
		edittingTagItemId,
		initialPicture = @CustomHelpers.PageToJavaScriptConverter(Model) ,
		initialTags = @CustomHelpers.TagsToJavaScriptConverter(Model.Tags.ToList()) ,
		jcropApi,
		deletedTags = [],
		addedTags = [],
		viewmodel = {
			picture: ko.observable(initialPicture),
			tagCollection: ko.observableArray(initialTags),
			createNewTag: function() {
				edittingTagItemId = 0;
				jcropApi = $.Jcrop('.cropable');
				$('#button-init-tag').hide();
				$('#button-destroy-tag').show();
				$('#button-save-tag').show();
			},
			cancelTag: function() {
				$('#button-init-tag').show();
				$('#button-destroy-tag').hide();
				$('#button-save-tag').hide();
				jcropApi.destroy();
			    $('#add-tag-modal').trigger('click'); 
			},
			saveTag: function() {
				$('#add-tag-div').show();
				$('#button-destroy-tag').hide();
				$('#button-save-tag').hide();
				$('#add-tag-modal').toggle();
			    $.fancybox.close();
			},
			finishSaveTag: function() {
				var selection = jcropApi.tellSelect(),
					position = selection.x + '_' + selection.y + '_' + selection.w + '_' + selection.h,
					convertedText = $('#converted-text').val(),
					translatedText = $('#translated-text').val(),
					newTag = new Tag(newlyCreatedTagId, position, convertedText, translatedText),
					added = {
						id: newlyCreatedTagId,
						position: position,
						convertedText: convertedText,
						translatedText: translatedText
					};
				addedTags[addedTags.length] = added;
				viewmodel.tagCollection.push(newTag);
				$('#button-init-tag').show();
				$('#add-tag-div').hide();
				$('#add-tag-modal').toggle();
				jcropApi.destroy();
				newlyCreatedTagId--;
			},
			cancelSaveTag: function() {
				$('#button-init-tag').show();
				$('#add-tag-div').hide();
				jcropApi.destroy();
			},
			saveAll: function() {
				$.ajax({
						url: '@Url.Action("SaveTags", "Pages")',
						type: 'POST',
						data: ko.toJSON({ deleted: deletedTags, added: addedTags, pageId: @Model.Id }),
						contentType: 'APPLICATION/JSON',
						success: function(result) {
							if (result.success) {

							} else {
								alert(result.message);
							}
						}
					});
			},
			fetchNextPicture: function() {
				$.ajax({
						url: '@Url.Action("FetchNextCommentPage", "Comments")',
						type: 'POST',
						data: ko.toJSON({ chapterId: viewmodel.chapterId, pageNumber: viewmodel.commentPageNo() + 1 }),
						contentType: 'APPLICATION/JSON',
						success: function(result) {
							if (result.isSuccess) {
								var listComment = [];
								$(result.comments).each(function(index, item) {
									listComment[index] = new Comment(item.id, item.username, item.content, item.createdDate, item.vote, item.isVotedUp, item.isVotedDown, item.isReported);
								});
								viewmodel.commentCollection(listComment);
								viewmodel.commentPageNo(viewmodel.commentPageNo() + 1);
								viewmodel.isDisablePrevBtn(viewmodel.commentPageNo() == 1);
								viewmodel.isDisableNextBtn(viewmodel.commentPageNo() == viewmodel.totalCommentPage());
							} else {
								alert(result.message);
							}
						}
					});
			}
		};
	ko.applyBindings(viewmodel);
	$("a#button-save-tag").fancybox({
		'modal': false,
		'showCloseButton':false,
		'hideOnOverlayClick':false
	});
	
</script>
